/*
 * @Descripttion:
 * @version:
 * @Author: cgy
 * @Date: 2025-10-13 11:51:36
 * @LastEditors: cgy
 * @LastEditTime: 2025-10-17 11:17:09
 * @Email: 452904906@qq.com
 */
package client

import (
	"gitee.com/huoyu123hk/cloudAgent/pkg/logx"
	"gitee.com/huoyu123hk/cloudAgent/pkg/proto/pb"
	"gitee.com/huoyu123hk/cloudAgent/pkg/shell"
)

type MessageHandler interface {
	HandleMessage(msg *pb.Message)
}

type handle struct {
	client *AgentClient
	shell  *shell.Shell
}

func NewHandle(c *AgentClient) *handle {
	return &handle{client: c}
}

func (c *handle) HandleMessage(msg *pb.Message) {
	switch msg.Type {
	case pb.Command_SHELL_EXEC:
		logx.Info("Received SHELL_EXEC message")
		req := msg.GetShellExecReq()
		s := shell.NewShell(req.Command, req.Env)
		c.shell = s
		err := s.Exec()
		if err != nil {
			logx.Errorf("Failed to exec shell: %v", err)
			return
		}
		logx.Info("Shell exec successfully")
		c.client.SendMessagePB(&pb.Message{
			RequestId: msg.RequestId,
			Type:      pb.Command_SHELL_EXEC,
			Payload: &pb.Message_ShellExecRes{
				ShellExecRes: &pb.ShellExecRes{
					Success: true,
				},
			},
		})

	case pb.Command_SHELL_DATA:
		logx.Info("Received SHELL_DATA message")
		data := msg.GetShellData()
		c.shell.Write(data.Data)

	case pb.Command_SHELL_RESIZE:
		logx.Info("Received SHELL_RESIZE message")
		req := msg.GetShellResize()
		c.shell.Resize(req.Rows, req.Cols)
	case pb.Command_SHELL_CLOSE:
		logx.Info("Received SHELL_CLOSE message")
		c.shell.Close()
	}

}
